package com.gwm.search;


import com.gwm.common.vo.PageResult;
import com.gwm.item.client.ItemClient;
import com.gwm.item.dto.SpuDTO;
import com.gwm.search.entity.Goods;
import com.gwm.search.repository.GoodsRepository;
import com.gwm.search.service.SearchService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 把数据库的数据全部导入进Es
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class GoodsESManager {

    @Autowired
    private SearchService searchService;
    @Autowired
    private ItemClient itemClient;
    @Autowired
    private GoodsRepository goodsRepository;
    /**
     * 从数据库查出数据 调用service的方法写入es
     */
    @Test
    public void initGoodsIndex(){
        int page = 1;
        int rows = 50;
        while(true){
            //分页  查询所有的spu信息
//            PageResult<SpuDTO> pageResult = itemClient.findSpuByPage(null, page, rows, true);
            PageResult<SpuDTO> pageResult = itemClient.findSpuPage(page, rows, null,true);
            if(pageResult == null || CollectionUtils.isEmpty(pageResult.getItems())){
                break;
            }
            List<SpuDTO> spuDTOList = pageResult.getItems();
            List<Goods> goodsList =  new ArrayList<>();
            for (SpuDTO spuDTO : spuDTOList) {
//            构造goods对象
                Goods goods = searchService.buildGoods(spuDTO);
                goodsList.add(goods);
            }
//          把goods对象 批量写入es
            goodsRepository.saveAll(goodsList);
            page ++;
        }

    }
}
